package com.sunnada.demo.service.serviceimpl;

import com.sunnada.demo.bean.User;
import com.sunnada.demo.dao.UserRepository;
import com.sunnada.demo.service.UserService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;


/**
 * @BelongsProject: mybatisproject2
 * @BelongsPackage: com.sunnada.demo.service.serviceimpl
 * @Author: 李瑞益
 * @CreateTime: 2018-10-10 09:36
 * @Description: 用户服务处实现类
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Override
    public void delete(int id) {
        User user = new User();
        user.setUid(id);
        userRepository.delete(user);
    }

    @Override
    public int insert(User user) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toString(); //盐量随机
        String encodedPassword= new SimpleHash("md5",user.getPassword(),salt,2).toString();
        user.setSalt(salt);
        user.setPassword(encodedPassword);
        User u = userRepository.save(user);
        if(u != null){
            return u.getUid();
        }

        return 0;
    }

    @Override
    public boolean update(User user) {
        userRepository.save(user);
        return false;
    }

    @Override
    public User getById(int id) {
        Optional<User> ou= userRepository.findById(id);
        if(ou.isPresent()){
            return ou.get();
        }
        return null;
    }

    @Override
    public List<User> getList() {
        return (List<User>)userRepository.findAll();
    }

    @Override
    public User findByName(String name) {
        return userRepository.findByName(name);
    }
}
